# -*- coding: utf-8 -*-

import os
import logging
from threading import Thread
from typing import List
from pathlib import Path

from fastapi import FastAPI, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from fastapi.responses import HTMLResponse

from app.scheduler import scheduler, init_scheduler
from app.worker.celery_worker import (
    test_celery,
    run_baidu_crawler,
    run_bilibili_crawler,
    run_kr36_crawler,
    run_hackernews_crawler,
    run_tieba_crawler,
    run_cankaoxiaoxi_crawler,
    run_xueqiu_crawler,
    run_douyin_crawler,
    run_fastbull_express_crawler,
    run_fastbull_news_crawler,
    run_gelonghui_crawler,
    run_thepaper_crawler,
    run_v2ex_crawler,
    run_ithome_crawler,
    run_zhihu_crawler,
    run_judge_worker,
    run_toutiao_crawler,
    run_weibo_crawler,
    run_ttl_worker
)

from app.source.source_controller import SourceController
from app.myttl.tts_automation import TTSAutomation
from app.myttl.tts_automation_dialogue import TTSDialogueAutomation
from app.monitor.status_page import get_monitor_page
from app.monitor import status_manager

log = logging.getLogger(__name__)

app = FastAPI()

# 配置静态文件服务
app.mount("/downloads", StaticFiles(directory="/app/downloads"), name="downloads")

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class TTSRequest(BaseModel):
    text: str

@app.on_event("startup")
async def startup_event():
    """启动时初始化调度器"""
    init_scheduler()

@app.get("/initsources")
async def init_sources():
    """初始化数据源"""
    controller = SourceController()
    controller.init_sources()
    return {"message": "Sources initialized"}

@app.get("/test/{word}")
async def test(word: str):
    """测试接口"""
    result = test_celery(word)
    return {"result": result}

@app.get("/crawl/baidu")
async def crawl_baidu():
    """爬取百度热搜"""
    result = run_baidu_crawler()
    return {"result": result}

@app.get("/crawl/weibo")
async def crawl_weibo():
    """爬取微博热搜"""
    result = run_weibo_crawler()
    return {"result": result}

@app.get("/crawl/toutiao")
async def crawl_toutiao():
    """爬取头条热榜"""
    result = run_toutiao_crawler()
    return {"result": result}

@app.get("/crawl/kr36")
async def crawl_kr36():
    """爬取36氪热榜"""
    result = run_kr36_crawler()
    return {"result": result}

@app.get("/crawl/bilibili")
async def crawl_bilibili():
    """爬取B站热搜"""
    result = run_bilibili_crawler()
    return {"result": result}

@app.get("/crawl/hackernews")
async def crawl_hackernews():
    """爬取Hacker News"""
    result = run_hackernews_crawler()
    return {"result": result}

@app.get("/crawl/tieba")
async def crawl_tieba():
    """爬取百度贴吧热门话题"""
    result = run_tieba_crawler()
    return {"result": result}

@app.get("/crawl/cankaoxiaoxi")
async def crawl_cankaoxiaoxi():
    """爬取参考消息"""
    result = run_cankaoxiaoxi_crawler()
    return {"result": result}

@app.get("/crawl/xueqiu")
async def crawl_xueqiu():
    """爬取雪球热门股票"""
    result = run_xueqiu_crawler()
    return {"result": result}

@app.get("/crawl/douyin")
async def crawl_douyin():
    """爬取抖音热搜"""
    result = run_douyin_crawler()
    return {"result": result}

@app.get("/crawl/fastbull/express")
async def crawl_fastbull_express():
    """爬取FastBull快讯"""
    result = run_fastbull_express_crawler()
    return {"result": result}

@app.get("/crawl/fastbull/news")
async def crawl_fastbull_news():
    """爬取FastBull新闻"""
    result = run_fastbull_news_crawler()
    return {"result": result}

@app.get("/crawl/gelonghui")
async def crawl_gelonghui():
    """爬取格隆汇"""
    result = run_gelonghui_crawler()
    return {"result": result}

@app.get("/crawl/thepaper")
async def crawl_thepaper():
    """爬取澎湃新闻"""
    result = run_thepaper_crawler()
    return {"result": result}

@app.get("/crawl/v2ex")
async def crawl_v2ex():
    """爬取V2EX"""
    result = run_v2ex_crawler()
    return {"result": result}

@app.get("/crawl/ithome")
async def crawl_ithome():
    """爬取IT之家"""
    result = run_ithome_crawler()
    return {"result": result}

@app.get("/crawl/zhihu")
async def crawl_zhihu():
    """爬取知乎热榜"""
    result = run_zhihu_crawler()
    return {"result": result}

@app.get("/crawl/judge")
async def crawl_judge():
    """爬取知乎热榜"""
    result = run_judge_worker()
    return {"result": result}

# 调度器管理接口
@app.get("/scheduler/jobs")
async def get_jobs():
    """获取所有定时任务"""
    jobs = []
    for job in scheduler.get_jobs():
        jobs.append({
            "id": job.id,
            "name": job.name,
            "next_run_time": str(job.next_run_time)
        })
    return {"jobs": jobs}

@app.post("/scheduler/pause/{job_id}")
async def pause_job(job_id: str):
    """暂停指定任务"""
    scheduler.pause_job(job_id)
    return {"message": f"Job {job_id} paused"}

@app.post("/scheduler/resume/{job_id}")
async def resume_job(job_id: str):
    """恢复指定任务"""
    scheduler.resume_job(job_id)
    return {"message": f"Job {job_id} resumed"}

@app.post("/scheduler/remove/{job_id}")
async def remove_job(job_id: str):
    """移除指定任务"""
    scheduler.remove_job(job_id)
    return {"message": f"Job {job_id} removed"}

@app.get("/api/tts")
async def convert_to_speech():
    """将文本转换为语音"""
    try:
        tts = TTSDialogueAutomation()
        tts.test_tts_automation_dialogue()
            
    except Exception as e:
        logger.error(f"TTS conversion failed: {str(e)}")
        return {"status": "error", "message": str(e)}

@app.get("/api/ttsjobs")
async def tts_jobs():
    """将文本转换为语音"""
    try:
        result = run_ttl_worker()
        return {"status": "success", "message": result}
            
    except Exception as e:
        logger.error(f"TTS conversion failed: {str(e)}")
        return {"status": "error", "message": str(e)}

# 添加文件列表API
@app.get("/api/files", response_model=List[dict])
async def list_files():
    """获取下载目录中的所有音频文件"""
    files = []
    downloads_path = Path("/app/downloads")
    
    if downloads_path.exists():
        for file_path in downloads_path.rglob("*.mp3"):
            relative_path = file_path.relative_to(downloads_path)
            files.append({
                "date": str(relative_path.parent),
                "filename": file_path.name,
                "url": f"/downloads/{relative_path}"
            })
    
    return files

@app.get("/monitor", response_class=HTMLResponse)
async def monitor_page():
    """显示监控页面"""
    return get_monitor_page()